from flask import Flask, request, jsonify
import pymysql

app = Flask(__name__)

# 数据库配置
DB_CONFIG = {
    'host': 'localhost',
    'user': 'root',
    'password': '123456',
    'database': 'cks',
    'charset': 'utf8mb4'
}

def get_db_connection():
    """获取数据库连接"""
    return pymysql.connect(**DB_CONFIG)

@app.route('/user/login', methods=['GET'])
def login():
    """用户登录接口"""
    # 获取请求参数
    username = request.args.get('username')
    password = request.args.get('password')

    # 检查参数是否提供
    if not username or not password:
        return jsonify({"status": 1, "msg": "用户名或密码不能为空", "data": {}}), 400

    try:
        # 数据库连接
        conn = get_db_connection()
        cursor = conn.cursor(pymysql.cursors.DictCursor)

        # 查询用户
        sql = "SELECT username, authority FROM user WHERE username = %s AND password = %s"
        cursor.execute(sql, (username, password))
        user = cursor.fetchone()

        # 检查用户是否存在
        if user:
            return jsonify({
                "status": 0,
                "msg": "登录成功",
                "data": {
                    "username": user['username'],
                    "authority": user['authority']
                }
            }), 200
        else:
            return jsonify({"status": 1, "msg": "用户名或密码错误", "data": {}}), 401
    except Exception as e:
        # 错误处理
        return jsonify({"status": 2, "msg": f"内部服务器错误: {str(e)}", "data": {}}), 500
    finally:
        # 关闭数据库连接
        if 'cursor' in locals():
            cursor.close()
        if 'conn' in locals():
            conn.close()
@app.route('/user/register', methods=['PUT'])
def register():
    """用户注册接口"""
    try:
        # 获取 JSON 数据
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        authority = data.get('authority')

        # 检查参数完整性
        if not username or not password or authority is None:
            return jsonify({"status": 1, "msg": "参数缺失"}), 400

        # 验证权限是否有效
        if authority not in [0, 1]:
            return jsonify({"status": 1, "msg": "权限值无效"}), 400

        # 数据库操作
        conn = get_db_connection()
        cursor = conn.cursor()

        # 检查用户名是否已存在
        check_sql = "SELECT COUNT(*) FROM user WHERE username = %s"
        cursor.execute(check_sql, (username,))
        if cursor.fetchone()[0] > 0:
            return jsonify({"status": 1, "msg": "用户名已存在"}), 409

        # 插入用户数据
        insert_sql = "INSERT INTO user (username, password, authority) VALUES (%s, %s, %s)"
        cursor.execute(insert_sql, (username, password, authority))
        conn.commit()

        return jsonify({"status": 0, "msg": "注册成功"}), 200

    except Exception as e:
        # 错误处理
        return jsonify({"status": 1, "msg": f"内部服务器错误: {str(e)}"}), 500
    finally:
        # 关闭数据库连接
        if 'cursor' in locals():
            cursor.close()
        if 'conn' in locals():
            conn.close()

@app.route('/keyword/getRank', methods=['GET'])
def get_rank():
    """获取搜索热度排行榜"""
    try:
        # 数据库操作
        conn = get_db_connection()
        cursor = conn.cursor()

        # 查询关键词搜索次数，按次数排序，取前 10 条
        query_sql = """
            SELECT historyKey, COUNT(*) AS searchNum
            FROM search_history
            GROUP BY historyKey
            ORDER BY searchNum DESC
            LIMIT 10;
        """
        cursor.execute(query_sql)
        results = cursor.fetchall()

        # 处理查询结果
        data = []
        for row in results:
            data.append({
                "keyword": row[0],
                "searchNum": str(row[1])
            })

        # 如果结果不足 10 条，补充 null
        while len(data) < 10:
            data.append({
                "keyword": None,
                "searchNum": None
            })

        return jsonify({"status": 0, "msg": "获取成功", "data": data}), 200

    except Exception as e:
        # 错误处理
        return jsonify({"status": 1, "msg": f"内部服务器错误: {str(e)}", "data": []}), 500
    finally:
        # 关闭数据库连接
        if 'cursor' in locals():
            cursor.close()
        if 'conn' in locals():
            conn.close()

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000, debug=True)
